﻿using NLog;
using System;
using System.IO;
using System.Threading.Tasks;
using Com.Lancetinc.Evs.Helpers;

namespace Com.Lancetinc.Evs.Communications
{
    /// <summary>
    /// 节拍协议
    /// </summary>
    public class BeatProtocolManager
    {
        private readonly IInstrumentManager instManager;
        private readonly Logger logger;
        private int validTicks = 0;
        // 节拍命令会让使用时间增加，调试的时候可以选择关闭
        private readonly bool _enableBeat = true;

        public BeatProtocolManager(IInstrumentManager instManager, Logger logger)
        {
            this.instManager = instManager;
            this.logger = logger;
#if DEBUG
            if (File.Exists(Path.Combine(DirUtil.ExeDirectory, "disable_beat.txt")))
            {
                _enableBeat = false;
            }
#endif
        }

        public void Tick()
        {
            if (!instManager.Instrument.VideoRecording)
                return;

            validTicks++;
            if (validTicks < 10)
                return;

            validTicks -= 10;
#if DEBUG
            if (!_enableBeat) return;
#endif
            Task.Factory.StartNew(() =>
            {
                try
                {
                    instManager.Send(PacketHelper.CreateBeat());
                }
                catch (Exception ex)
                {
                    logger.Error(ex.Message);
                }
            });
        }
    }
}
